<?php
/**
 * Created by PhpStorm.
 * User: 毛文科
 * Date: 2018/8/23 0023
 * Time: 13:54
 */
namespace app\admin\model;
use think\Db;

class NoticeModel
{
    /**获取公告模型
     * @return $this
     */
    static public function getNotice($true=true){
        if($true){
            return Db::view('notice',true)
                ->view('user','user,openid,nickname,portrait,sex,phone,email,integral,fabulous','user.id=notice.author','left')
                ->view('departmen_table','departmen_name,number','departmen_table.id=notice.notice_type')
                ->json(['picture']);
        }else{
            return Db::view('notice',true)
                ->view('user','user,openid,nickname,portrait,sex,phone,email,integral,fabulous','user.id=notice.author','left')
                ->json(['picture']);
        }
    }

    /**添加公告
     * @param $data
     * @return int|string
     */
    static public function addNotice($data){
        if(isset($data['picture'])){
            return Db::name('notice')->json(['picture'])->insert($data);
        }else{
            return Db::name('notice')->insert($data);
        }
    }

    /**删除公告
     * @param $field
     * @param null $op
     * @param null $condition
     * @return int
     */
    static public function delNotice($field, $op = null, $condition = null){
        $sul = Db::connect();
        $notices = $sul->name('notice')->json(['picture'])->where($field,$op,$condition)->select();
        foreach ($notices as $notice){
            if(is_array($notice['picture'])){
                foreach ($notice['picture'] as $value){
                    if(is_file(config('FileRoot').$value)){
                        unlink(config('FileRoot').$value);
                    }
                }
            }
        }
        return $sul->name('notice')->where($field,$op,$condition)->delete();
    }

    /**更新公告
     * @param $data
     * @return int|string
     */
    static public function updateNotice($data){
        $sul = Db::connect();
        if(isset($data['picture'])&&is_array($data['picture'])){
            $notice = $sul->name('notice')->json(['picture'])->where('id',$data['id'])->find();
            if(is_array($notice['picture'])){
                foreach ($notice['picture'] as $value){
                    if(is_file(config('FileRoot').$value)){
                        unlink(config('FileRoot').$value);
                    }
                }
            }
        }
        return $sul->name('notice')->json(['picture'])->update($data);
    }
}